<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;

/**
 * 排程算法优化
 * @icon fa fa-cogs
 * @remark 智能排程算法优化，为生产计划提供优化建议
 */
class ScheduleTask extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\ScheduleTask;
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->alias('st')
                ->join('scanwork_schedule s', 'st.schedule_id = s.id', 'LEFT')
                ->join('scanwork_process p', 'st.process_id = p.id', 'LEFT')
                ->join('scanwork_work_center w', 'st.work_center_id = w.id', 'LEFT')
                ->join('scanwork_equipment e', 'st.equipment_id = e.id', 'LEFT')
                ->join('scanwork_employee emp', 'st.employee_id = emp.id', 'LEFT')
                ->where($where)
                ->field('st.*, s.schedule_name, p.name as process_name, w.center_name, e.equipment_name, emp.employee_name')
                ->order($sort, $order)
                ->paginate($limit);
            return json(["total" => $list->total(), "rows" => $list->items()]);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 验证必填字段
                if (empty($params['schedule_id'])) {
                    $this->error('请选择排程');
                }
                if (empty($params['process_id'])) {
                    $this->error('请选择工序');
                }
                
                // 自动生成任务编号
                if (empty($params['task_no'])) {
                    $params['task_no'] = 'TASK' . date('Ymd') . sprintf('%04d', rand(1, 9999));
                }
                
                // 转换时间格式为时间戳
                if (!empty($params['plan_start_time'])) {
                    $params['plan_start_time'] = is_numeric($params['plan_start_time']) ? $params['plan_start_time'] : strtotime($params['plan_start_time']);
                }
                if (!empty($params['plan_end_time'])) {
                    $params['plan_end_time'] = is_numeric($params['plan_end_time']) ? $params['plan_end_time'] : strtotime($params['plan_end_time']);
                }
                
                // 计算计划时间
                if (!empty($params['quantity']) && !empty($params['standard_time'])) {
                    $totalTime = $params['quantity'] * $params['standard_time'] + ($params['setup_time'] ?: 0);
                    if (!empty($params['plan_start_time'])) {
                        $params['plan_end_time'] = $params['plan_start_time'] + $totalTime * 3600;
                    }
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取排程列表
        $scheduleList = Db::name('scanwork_schedule')->where('status', 'in', [1, 2])->select();
        $this->view->assign('scheduleList', $scheduleList);
        
        // 获取工序列表
        $processList = Db::name('scanwork_process')->where('status', 1)->select();
        $this->view->assign('processList', $processList);
        
        // 获取工作中心列表
        $workCenterList = Db::name('scanwork_work_center')->where('status', 1)->select();
        $this->view->assign('workCenterList', $workCenterList);
        
        // 获取设备列表
        $equipmentList = Db::name('scanwork_equipment')->where('status', 1)->select();
        $this->view->assign('equipmentList', $equipmentList);
        
        // 获取员工列表
        $employeeList = Db::name('scanwork_employee')->where('status', 1)->select();
        $this->view->assign('employeeList', $employeeList);
        
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 验证必填字段
                if (empty($params['schedule_id'])) {
                    $this->error('请选择排程');
                }
                if (empty($params['process_id'])) {
                    $this->error('请选择工序');
                }
                
                // 转换时间格式为时间戳
                if (!empty($params['plan_start_time'])) {
                    $params['plan_start_time'] = is_numeric($params['plan_start_time']) ? $params['plan_start_time'] : strtotime($params['plan_start_time']);
                }
                if (!empty($params['plan_end_time'])) {
                    $params['plan_end_time'] = is_numeric($params['plan_end_time']) ? $params['plan_end_time'] : strtotime($params['plan_end_time']);
                }
                
                // 计算计划时间
                if (!empty($params['quantity']) && !empty($params['standard_time'])) {
                    $totalTime = $params['quantity'] * $params['standard_time'] + ($params['setup_time'] ?: 0);
                    if (!empty($params['plan_start_time'])) {
                        $params['plan_end_time'] = $params['plan_start_time'] + $totalTime * 3600;
                    }
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取排程列表
        $scheduleList = Db::name('scanwork_schedule')->where('status', 'in', [1, 2])->select();
        $this->view->assign('scheduleList', $scheduleList);
        
        // 获取工序列表
        $processList = Db::name('scanwork_process')->where('status', 1)->select();
        $this->view->assign('processList', $processList);
        
        // 获取工作中心列表
        $workCenterList = Db::name('scanwork_work_center')->where('status', 1)->select();
        $this->view->assign('workCenterList', $workCenterList);
        
        // 获取设备列表
        $equipmentList = Db::name('scanwork_equipment')->where('status', 1)->select();
        $this->view->assign('equipmentList', $equipmentList);
        
        // 获取员工列表
        $employeeList = Db::name('scanwork_employee')->where('status', 1)->select();
        $this->view->assign('employeeList', $employeeList);
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($pk, 'in', $ids)->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 智能排程算法优化
     */
    public function optimize()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $algorithm = $params['algorithm'] ?? 'priority';
            $constraints = $params['constraints'] ?? [];
            
            // 调用排程引擎进行优化
            $scheduleEngine = new \app\admin\library\ScheduleEngine();
            $result = $scheduleEngine->execute($algorithm, $constraints);
            
            if ($result['success']) {
                $this->success('排程优化完成', '', $result['data']);
            } else {
                $this->error($result['message']);
            }
        }
        
        // 获取可用的算法选项
        $algorithms = [
            'priority' => '优先级排程',
            'finite_capacity' => '有限产能排程',
            'cyclic' => '循环排程'
        ];
        
        $this->view->assign('algorithms', $algorithms);
        return $this->view->fetch();
    }

    /**
     * 获取排程建议
     */
    public function getSuggestions()
    {
        if ($this->request->isAjax()) {
            $scheduleId = $this->request->param('schedule_id');
            if (empty($scheduleId)) {
                $this->error('请选择排程计划');
            }
            
            // 获取当前排程的任务
            $tasks = $this->model->where('schedule_id', $scheduleId)->select();
            
            // 分析排程并提供优化建议
            $suggestions = $this->analyzeSchedule($tasks);
            
            $this->success('获取成功', '', $suggestions);
        }
    }

    /**
     * 分析排程并提供建议
     */
    private function analyzeSchedule($tasks)
    {
        $suggestions = [];
        
        // 分析设备利用率
        $equipmentUtilization = $this->calculateEquipmentUtilization($tasks);
        if ($equipmentUtilization['low'] > 0) {
            $suggestions[] = [
                'type' => 'warning',
                'title' => '设备利用率偏低',
                'message' => "有{$equipmentUtilization['low']}台设备利用率低于70%，建议重新分配任务"
            ];
        }
        
        // 分析任务冲突
        $conflicts = $this->detectConflicts($tasks);
        if (!empty($conflicts)) {
            $suggestions[] = [
                'type' => 'error',
                'title' => '发现任务冲突',
                'message' => "发现" . count($conflicts) . "个任务时间冲突，需要调整"
            ];
        }
        
        return $suggestions;
    }

    /**
     * 计算设备利用率
     */
    private function calculateEquipmentUtilization($tasks)
    {
        $equipmentStats = [];
        foreach ($tasks as $task) {
            if ($task['equipment_id']) {
                $equipmentId = $task['equipment_id'];
                if (!isset($equipmentStats[$equipmentId])) {
                    $equipmentStats[$equipmentId] = ['total_time' => 0, 'planned_time' => 0];
                }
                $equipmentStats[$equipmentId]['planned_time'] += $task['standard_time'] ?? 0;
            }
        }
        
        $low = 0;
        foreach ($equipmentStats as $stats) {
            $utilization = $stats['planned_time'] / 8; // 假设8小时工作制
            if ($utilization < 0.7) {
                $low++;
            }
        }
        
        return ['low' => $low, 'stats' => $equipmentStats];
    }

    /**
     * 检测任务冲突
     */
    private function detectConflicts($tasks)
    {
        $conflicts = [];
        $equipmentTasks = [];
        
        foreach ($tasks as $task) {
            if ($task['equipment_id'] && $task['plan_start_time'] && $task['plan_end_time']) {
                $equipmentId = $task['equipment_id'];
                if (!isset($equipmentTasks[$equipmentId])) {
                    $equipmentTasks[$equipmentId] = [];
                }
                $equipmentTasks[$equipmentId][] = $task;
            }
        }
        
        foreach ($equipmentTasks as $equipmentId => $tasks) {
            for ($i = 0; $i < count($tasks); $i++) {
                for ($j = $i + 1; $j < count($tasks); $j++) {
                    $task1 = $tasks[$i];
                    $task2 = $tasks[$j];
                    
                    if ($this->isTimeConflict($task1, $task2)) {
                        $conflicts[] = [
                            'equipment_id' => $equipmentId,
                            'task1_id' => $task1['id'],
                            'task2_id' => $task2['id']
                        ];
                    }
                }
            }
        }
        
        return $conflicts;
    }

    /**
     * 检查时间冲突
     */
    private function isTimeConflict($task1, $task2)
    {
        $start1 = $task1['plan_start_time'];
        $end1 = $task1['plan_end_time'];
        $start2 = $task2['plan_start_time'];
        $end2 = $task2['plan_end_time'];
        
        return !($end1 <= $start2 || $end2 <= $start1);
    }
}
